<template>
  <div class="purchase-request-list">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3 class="title">采购申请列表</h3>
          <el-button type="primary" :icon="Plus" @click="$router.push('/purchase-requests/create')">新建采购申请</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" class="search-form" @keyup.enter="handleSearch">
          <div class="form-row">
            <el-form-item label="物品名称" class="search-item">
              <el-input 
                v-model="searchForm.itemName" 
                placeholder="请输入物品名称" 
                clearable
                :prefix-icon="Search"
              />
            </el-form-item>
            <el-form-item label="申请状态" class="search-item">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option label="待审批" value="PENDING" />
                <el-option label="已通过" value="APPROVED" />
                <el-option label="已拒绝" value="REJECTED" />
              </el-select>
            </el-form-item>
            <el-form-item label="申请日期" class="search-item date-item">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :prefix-icon="Calendar"
              />
            </el-form-item>
            <div class="button-group">
              <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </div>
          </div>
        </el-form>
      </div>
      
      <!-- 表格内容区 -->
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="purchaseRequests"
          style="width: 100%"
          border
          stripe
          highlight-current-row
        >
          <el-table-column prop="id" label="编号" width="80" align="center" />
          <el-table-column prop="itemName" label="物品名称" min-width="120" show-overflow-tooltip />
          <el-table-column prop="quantity" label="数量" width="80" align="center" />
          <el-table-column prop="budget" label="预算" width="120" align="right">
            <template #default="scope">
              <span class="budget">¥{{ scope.row.budget.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="reason" label="申请理由" min-width="150" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)" size="small">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="申请日期" width="180" align="center">
            <template #default="scope">
              <el-tooltip 
                :content="formatDateTime(scope.row.createdAt)" 
                placement="top"
                :show-after="1000"
              >
                <span>{{ formatDateTime(scope.row.createdAt) }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="scope">
              <el-button 
                link 
                type="primary" 
                :icon="View"
                @click="viewDetail(scope.row.id)"
              >
                查看
              </el-button>
              <el-button 
                v-if="scope.row.status === 'PENDING'"
                link 
                type="primary" 
                :icon="Edit"
                @click="editRequest(scope.row.id)"
              >
                编辑
              </el-button>
              <el-button 
                v-if="scope.row.status === 'PENDING'"
                link 
                type="danger" 
                :icon="Delete"
                @click="confirmDelete(scope.row.id)"
              >
                删除
              </el-button>
              <el-button
                v-if="scope.row.attachmentUrl"
                link
                type="info"
                :icon="Download"
                @click="downloadAttachment(scope.row.id, scope.row.attachmentUrl)"
              >
                下载附件
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPurchaseRequests, deletePurchaseRequest } from '@/api/purchase-request'
import { formatDateTime } from '@/utils/format'
import { useRouter } from 'vue-router'
import { 
  Search, 
  Refresh, 
  Calendar, 
  View, 
  Edit, 
  Delete, 
  Download,
  Plus
} from '@element-plus/icons-vue'

const router = useRouter()
const loading = ref(false)
const purchaseRequests = ref([])

// 搜索表单
const searchForm = ref({
  itemName: '',
  status: '',
  dateRange: []
})

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取采购申请列表
const fetchPurchaseRequests = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      itemName: searchForm.value.itemName || undefined,
      status: searchForm.value.status || undefined,
      startDate: searchForm.value.dateRange && searchForm.value.dateRange[0] ? searchForm.value.dateRange[0] : undefined,
      endDate: searchForm.value.dateRange && searchForm.value.dateRange[1] ? searchForm.value.dateRange[1] : undefined
    }
    
    console.log('搜索参数:', params)
    
    const response = await getPurchaseRequests(params)
    console.log('API响应:', response)
    
    purchaseRequests.value = response.content
    total.value = response.totalElements
  } catch (error) {
    console.error('获取采购申请列表失败:', error)
    ElMessage.error('获取采购申请列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPurchaseRequests()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.itemName = ''
  searchForm.value.status = ''
  searchForm.value.dateRange = []
  currentPage.value = 1
  fetchPurchaseRequests()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchPurchaseRequests()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPurchaseRequests()
}

// 查看详情
const viewDetail = (id) => {
  router.push(`/purchase-requests/${id}`)
}

// 编辑请求
const editRequest = (id) => {
  router.push(`/purchase-requests/${id}/edit`)
}

// 确认删除
const confirmDelete = (id) => {
  ElMessageBox.confirm(
    '确定要删除这条采购申请吗？此操作不可逆。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteRequest(id)
  }).catch(() => {})
}

// 删除请求
const deleteRequest = async (id) => {
  try {
    await deletePurchaseRequest(id)
    ElMessage.success('删除成功')
    fetchPurchaseRequests()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 下载附件
const downloadAttachment = (id, url) => {
  window.open(url, '_blank')
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'PENDING': return 'warning'
    case 'APPROVED': return 'success'
    case 'REJECTED': return 'danger'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'PENDING': return '待审批'
    case 'APPROVED': return '已通过'
    case 'REJECTED': return '已拒绝'
    default: return '未知'
  }
}

onMounted(() => {
  fetchPurchaseRequests()
})
</script>

<style scoped>
.purchase-request-list {
  padding: 20px;
  height: 100%;
  min-height: calc(100vh - 120px);
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 0;
  border-bottom: 1px solid #ebeef5;
}

.title {
  margin: 0;
  padding: 15px 20px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.search-section {
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
}

.search-form {
  width: 100%;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-start;
}

.search-item {
  margin-bottom: 0;
  flex: 1;
  min-width: 200px;
}

.date-item {
  flex: 2;
  min-width: 360px;
}

.button-group {
  display: flex;
  gap: 8px;
  margin-left: auto;
  align-self: flex-end;
}

.table-section {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
}

:deep(.el-table) {
  flex: 1;
  min-height: 0;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
  min-height: 200px;
  max-height: calc(100vh - 400px);
}

:deep(.el-table .cell) {
  padding: 8px;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

.budget {
  font-family: monospace;
  color: #67c23a;
}

.pagination-section {
  position: relative;
  z-index: 1;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: auto;
}

:deep(.el-pagination) {
  padding: 0;
  margin: 0;
  justify-content: flex-end;
  white-space: nowrap;
}

:deep(.el-card__body) {
  height: 100%;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 0;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .search-item {
    min-width: 180px;
  }
  
  .date-item {
    min-width: 300px;
  }
}

@media screen and (max-width: 768px) {
  .search-item,
  .date-item {
    flex: 1 1 100%;
  }
  
  .button-group {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 